/**
 * 
 */

/**
 * Calculates a given postfix expression
 * @author Michael Fildestine ID:309161594
 *
 */
public class PostfixCalculator extends Calculator {
	
	private StackAsArray myStack = new StackAsArray();
	private double result;
	
	
		
	/**
	 * Evaluates a given postfix expression.
	 * @param expr a legal post fix expression represented as a String 
	 */
	public void evaluate(String expr){
		// Break the expression into tokens.
		ExpTokenizer tokenizer = new ExpTokenizer(expr);
		//While tokens remain we push them into the expandable stack.
		while (tokenizer.hasMoreTokens()){
			Object token = tokenizer.nextElement();
			if (token instanceof BinaryOp){										//if the next token is an operator , we pop the previous two numbers out of the stack and 
				ValueToken right = (ValueToken)myStack.pop();					//Perform the operation on them , and then push the result back in the stack.
				ValueToken left = (ValueToken)myStack.pop();
				ValueToken sol = new ValueToken(((BinaryOp)token).operate(left.getValue(), right.getValue()));
				myStack.push(sol);
			}else{								// if the next token is a number we simply push it in the stock.
				this.myStack.push(token);
			}
		
		}
		this.result = ((ValueToken)myStack.pop()).getValue();  //saves the result in the private field.
	}
	/**
	 * @return Current result form the last postfix calculation.
	 */
	public double getCurrentResult(){
		return this.result;
	}
	
	
	
	

}
